<?php
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/19 10:56
 * Desc: 积分抽奖
 */
class Model_Api_V2_Integral_Award
{
    /**
     * @function 获取奖品
     * @return mixed
     */
    public function is_luck($id)
    {
        $suit = DB::select()
            ->from('integral_award_suit')
            ->where('award_id', '=', $id)
            ->execute()
            ->as_array();
        //重新计算概率
        $total = 0;
        foreach ($suit as &$v) {
            if ($v['number'] > 0) {
                $total += $v['percentage'];
            } else {
                $v['percentage'] = 0;
            }
        }
        if ($total) {
            foreach ($suit as &$v) {
                $v['percentage'] = ceil($v['percentage'] / $total * 100);
            }
        }
        return $this->get_award($suit);
    }

    /**
     * 获取奖品
     * @param $data
     * @return mixed
     */
    public function get_award($data)
    {
        $arr = array();
        usort($data, array($this, 'sort'));
        foreach ($data as $key => $val) {
            $arr[$key + 1] = $val['percentage'];
        }
        $rid   = $this->get_rand($arr);
        return $data[$rid - 1];
    }

    /**
     * 排序
     * @param $obj
     * @param $next_obj
     * @return int
     */
    public function sort($obj, $next_obj)
    {
        return $obj['percentage'] > $next_obj['percentage'] ? -1 : 1;
    }

    /**
     * @function 抽奖算法
     * @param $pro_arr
     * @return int|string
     */
    public function get_rand($pro_arr)
    {
        $result = '';
        //概率数组的总概率精度
        $pro_sum = array_sum($pro_arr);
        //概率数组循环
        foreach ($pro_arr as $key => $pro_cur) {
            $rand_num = mt_rand(1, $pro_sum);
            if ($rand_num <= $pro_cur) {
                $result = $key;
                break;
            } else {
                $pro_sum -= $pro_cur;
            }
        }
        unset ($pro_arr);
        return $result;
    }
}